package org.jeecg.modules.htxincailiao.forums.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.RequestUtil;
import org.jeecg.common.util.SmartBeanUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.forums.entity.HTForumsAnswer;
import org.jeecg.modules.htxincailiao.forums.entity.HTForumsQuestion;
import org.jeecg.modules.htxincailiao.forums.service.IHTForumsAnswerService;
import org.jeecg.modules.htxincailiao.forums.service.IHTForumsQuestionService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: ht_forums_question
 * @Author: jeecg-boot
 * @Date:   2021-07-15
 * @Version: V1.0
 */
@Api(tags="ht_forums_question")
@RestController
@RequestMapping("/forums/hTForumsQuestion")
@Slf4j
public class HTForumsQuestionController extends JeecgController<HTForumsQuestion, IHTForumsQuestionService> {
	@Resource
	private IHTForumsQuestionService hTForumsQuestionService;

	@Resource
	private IHTForumsAnswerService ihtForumsAnswerService;

	 @Resource
	 private RedisUtil redisUtil;

	 @Resource
	 private IHTAccountService accountService;

	 @Resource
	 private ISysUserService sysUserService;

	/**
	 * 分页列表查询
	 *
	 * @param hTForumsQuestion
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_forums_question-分页列表查询")
	@ApiOperation(value="ht_forums_question-分页列表查询", notes="ht_forums_question-分页列表查询")
	@RequestMapping(value = "/list", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> queryPageList(HTForumsQuestion hTForumsQuestion,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		log.info("\n\npageList : {}\n\n", hTForumsQuestion );
		if (req.getMethod().equals("POST")){
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				hTForumsQuestion = JSONObject.parseObject(line, HTForumsQuestion.class);
				pageNo = oConvertUtils.isNotEmpty(hTForumsQuestion.getPageNo())  ? hTForumsQuestion.getPageNo() : pageNo;
				pageSize =oConvertUtils.isNotEmpty(hTForumsQuestion.getPageNo())  ? hTForumsQuestion.getPageSize() : pageSize;
			}
		}

		if(oConvertUtils.isNotEmpty(hTForumsQuestion) &&
				oConvertUtils.isNotEmpty(hTForumsQuestion.getCategoryId()) &&
				hTForumsQuestion.getCategoryId().equals("0")) {
			//全部分类
			hTForumsQuestion.setCategoryId(null);
		}

		QueryWrapper<HTForumsQuestion> queryWrapper = QueryGenerator.initQueryWrapper(hTForumsQuestion, req.getParameterMap());
		queryWrapper.orderByDesc("update_time");
		Page<HTForumsQuestion> page = new Page<HTForumsQuestion>(pageNo, pageSize);
		IPage<HTForumsQuestion> pageList = hTForumsQuestionService.page(page, queryWrapper);

		if (pageList.getTotal() > 0) {
			for (HTForumsQuestion question: pageList.getRecords()) {
				LambdaQueryWrapper<HTForumsAnswer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
				lambdaQueryWrapper.eq(HTForumsAnswer::getQuestionId, question.getId());
				List<HTForumsAnswer> list = ihtForumsAnswerService.list(lambdaQueryWrapper);
				question.setAnswerList(list);
			}
		}


		return Result.OK(pageList);
	}	/**
	 * 分页列表查询
	 *
	 * @param hTForumsQuestion
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_forums_question-分页列表查询")
	@ApiOperation(value="ht_forums_question-分页列表查询", notes="ht_forums_question-分页列表查询")
	@RequestMapping(value = "/pc-home-list", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> queryPCHomePageList(HTForumsQuestion hTForumsQuestion,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		if (req.getMethod().equals("POST")){
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				hTForumsQuestion = JSONObject.parseObject(line, HTForumsQuestion.class);
				pageNo = oConvertUtils.isNotEmpty(hTForumsQuestion.getPageNo())  ? hTForumsQuestion.getPageNo() : pageNo;
				pageSize =oConvertUtils.isNotEmpty(hTForumsQuestion.getPageNo())  ? hTForumsQuestion.getPageSize() : pageSize;
			}
		}

		if(oConvertUtils.isNotEmpty(hTForumsQuestion) &&
				oConvertUtils.isNotEmpty(hTForumsQuestion.getCategoryId()) &&
				hTForumsQuestion.getCategoryId().equals("0")) {
			//全部分类
			hTForumsQuestion.setCategoryId(null);
		}

		QueryWrapper<HTForumsQuestion> queryWrapper = QueryGenerator.initQueryWrapper(hTForumsQuestion, req.getParameterMap());
		queryWrapper.orderByDesc("is_home_recommended").orderByDesc("update_time");

		Page<HTForumsQuestion> page = new Page<HTForumsQuestion>(pageNo, pageSize);
		IPage<HTForumsQuestion> pageList = hTForumsQuestionService.page(page, queryWrapper);


		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param hTForumsQuestion
	 * @return
	 */
	@AutoLog(value = "ht_forums_question-添加")
	@ApiOperation(value="ht_forums_question-添加", notes="ht_forums_question-添加")
	@PostMapping(value = "/add")
	public Result<?> add(HttpServletRequest request, @RequestBody HTForumsQuestion hTForumsQuestion) {
		String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		if(oConvertUtils.isEmpty(token)) {
			return Result.error("请先登录！");
		}
		String username = JwtUtil.getUsername(token);

		//1. 通过登录账号、手机号、
		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);

		if(oConvertUtils.isEmpty(user)){
			//是否为后台登录用户
			SysUser sysUser = sysUserService.getUserByName(username) ;
			user = SmartBeanUtil.copy(sysUser, HTPlatformUser.class);
		}
		if (oConvertUtils.isEmpty(user)){
			return Result.error("用户未登录");
		}
		else {
			hTForumsQuestion.setAskUserId(user.getId());
		}

		hTForumsQuestionService.save(hTForumsQuestion);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param hTForumsQuestion
	 * @return
	 */
	@AutoLog(value = "ht_forums_question-编辑")
	@ApiOperation(value="ht_forums_question-编辑", notes="ht_forums_question-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody HTForumsQuestion hTForumsQuestion) {
		hTForumsQuestionService.updateById(hTForumsQuestion);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_forums_question-通过id删除")
	@ApiOperation(value="ht_forums_question-通过id删除", notes="ht_forums_question-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		hTForumsQuestionService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ht_forums_question-批量删除")
	@ApiOperation(value="ht_forums_question-批量删除", notes="ht_forums_question-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hTForumsQuestionService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_forums_question-通过id查询")
	@ApiOperation(value="ht_forums_question-通过id查询", notes="ht_forums_question-通过id查询")
    @RequestMapping(value = "/queryById", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> queryById(HttpServletRequest req, @RequestParam(name="id",required=false) String id) {
		if (req.getMethod().equals("POST")){
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				HTForumsQuestion hTForumsQuestion  = JSONObject.parseObject(line, HTForumsQuestion.class);
				id = hTForumsQuestion.getId();
			}
		}

		HTForumsQuestion hTForumsQuestion = hTForumsQuestionService.getById(id);
		if(hTForumsQuestion==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hTForumsQuestion);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hTForumsQuestion
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HTForumsQuestion hTForumsQuestion) {
        return super.exportXls(request, hTForumsQuestion, HTForumsQuestion.class, "ht_forums_question");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTForumsQuestion.class);
    }

}
